import json
import time

# 路由列表    路径　　　函数引用
# 增加了框架可维护性　　　app的代码不用做任何修改可以直接添加功能　　django框架添加路由方式
import pymysql

route_list = []


def get_time():
    return time.ctime()
route_list.append(("/gettime.html",get_time))


def index():
    '''当前用户请求/index.html 执行当前函数'''
    # 1.将模板文件从磁盘读取到内存中
    with open("./template/index.html","r",encoding = "utf-8") as file:
        html_data = file.read()
    # 2.将数据从数据库中读取出来
    conn = pymysql.connect(host = "192.168.199.132",port = 3306, user = "root", password = "mysql", db = "stock_db", charset = "utf8")
    cur = conn.cursor()
    cur.execute("select * from info")
    data = cur.fetchall()
    cur.close()
    conn.close()
    # 3.将模板文件进行替换（把占位符替换为用户所需要的数据）
    stock_data = ""
    for line in data:
        line_str = '''<tr>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td><input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007"></td>
                   </tr>''' % line
        stock_data += line_str
    html_data = html_data.replace("{%content%}",stock_data)
    return html_data
route_list.append(("/index.html",index))


def center():
    with open("./template/center.html","r",encoding='utf-8') as f:
        html_data = f.read()
    html_data = html_data.replace('{%content%}','')
    return html_data
route_list.append(('/center.html',center))

def center_data():
    sql = "select i.code, i.short,i.chg,i.turnover,i.price,i.highs,focus.note_info from info i inner join focus on i.id = focus.info_id;"
    conn = pymysql.connect(host="192.168.199.132", port=3306, user="root", password="mysql", db="stock_db",
                           charset="utf8")
    cur = conn.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    cur.close()
    conn.close()
    data_list = list()
    for row in data:
        data_dict = dict()
        data_dict["code"] = row[0]
        data_dict["short"] = row[1]
        data_dict["chg"] = row[2]
        data_dict["turnover"] = row[3]
        data_dict["price"] = str(row[4])
        data_dict["highs"] = str(row[5])
        data_dict["note_info"] = row[6]
        data_list.append(data_dict)

    json_data = json.dumps(data_list,ensure_ascii=False)
    return json_data
route_list.append(('/center_data.html',center_data))

def app(env):
    path_info = env["PATH_INFO"]
    print("框架收到动态资源请求 %s" % path_info)
    for path, func in route_list:
        if path == path_info:
            return '200OK',[("server","APP1.1")], func()
    else:
        return '404 NotFound',[("server","APP1.1")],"hello world"
